package ta.web.servlet;

import org.apache.commons.beanutils.BeanUtils;
import ta.dao.UserDao;
import ta.pojo.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "backLoginServlet",urlPatterns = "/backLoginServlet")
public class backLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String type=request.getParameter("type");
		switch (type)
		{
		case "login":
			login(request, response);
			break;

        case "logout":
        	logout(request, response);
			break;
		}		
	}

	protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		 Map<String, String[]> map=request.getParameterMap();
		 User user=new User();
		 try {
			BeanUtils.populate(user, map);
		} catch (IllegalAccessException | InvocationTargetException e)
		{			
			e.printStackTrace();
		}
		//user.setUserpwd(DES.encrypt(user.getUserpwd()));
		UserDao  dao=new  UserDao();	
		  //连接数据库
		   if(dao.login(user))
		   {
			   //存session 用户名
			   request.getSession().setAttribute("loginame",user.getUsername());
			   //跳转到管理页面
			   response.sendRedirect("admin.jsp");
		   }
		   else{
			   response.setCharacterEncoding("utf-8");
			   response.setContentType("text/html; charset=UTF-8");
			   response.getWriter().print("<script>alert('账号密码不匹配，请检查后重新登录！')</script>");
			   response.setHeader("refresh","0.1;url=login.jsp");
		   }		
	}
	
	protected void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().removeAttribute("loginame");
		response.sendRedirect("index.jsp");
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		doGet(request, response);
	}
	
	

}
